<script setup lang="ts">
import { ref } from 'vue'
import { FormInstance, Message } from '@arco-design/web-vue'
import { useRouter, useRoute } from 'vue-router'
import { IconUser, IconLock } from '@arco-design/web-vue/es/icon'
import { encrypt } from '@/utils/auth'
import { getPublicKeyUsingGet } from '@/api/authController'
import { userLoginUsingPost } from '@/api/userController'
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const contactVisible = ref(false)
const publicKeyName = 'jiyan-publicKey'
const contactForm = ref({
  email: '',
  reason: ''
})
const formRef = ref<FormInstance | null>(null)
const formData = ref({
  username: '',
  orginalPassword: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    { minLength: 8, message: '用户名长度不能小于8位' },
    { maxLength: 32, message: '用户名长度不能超过32位' }
  ],
  orginalPassword: [
    { required: true, message: '请输入密码' },
    { minLength: 8, message: '密码长度不能小于8位' },
    { maxLength: 32, message: '密码长度不能超过32位' }
  ]
}

const handleSubmit = async () => {
  loading.value = true
  try {
    if (!formRef.value) return
    const errorValid = await formRef.value.validate()
    if (errorValid) {
      return
    }
    const publicKey: any = await getPublicKeyUsingGet()
    formData.value.password = encrypt(formData.value.orginalPassword, publicKey)

    const res: any = await userLoginUsingPost(formData.value)
    console.log(res)
    if (res?.code == 0) {
      Message.success('登录成功')
      formData.value = {
        username: '',
        orginalPassword: '',
        password: ''
      }

      const redirect = route.query.redirect as string
      router.push(redirect || '/')
    } else {
      Message.error(res?.message || '登录失败')
    }
  } catch (error) {
    Message.error('登录失败' + error)
  } finally {
    loading.value = false
  }
}

const showContactAdmin = () => {
  contactVisible.value = true
}

const handleContactSubmit = () => {
  Message.success('消息已发送，管理员会尽快处理')
  contactVisible.value = false
  contactForm.value = {
    email: '',
    reason: ''
  }
}


const goToHelp = () => {
  router.push('/help')
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="header">
      <div class="logo">极研协作</div>
    </div>

    <div class="login-box">
      <h1 class="title">登录极研协作</h1>

      <a-form
        :model="formData"
        @submit="handleSubmit"
        class="login-form"
        :rules="rules"
        ref="formRef"
      >
        <div class="form-header">
          <h2 class="form-title">账号登录</h2>
        </div>

        <a-form-item field="username" validate-trigger="blur">
          <a-input v-model="formData.username" placeholder="请输入用户名" allow-clear>
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item field="orginalPassword" validate-trigger="blur">
          <a-input-password v-model="formData.orginalPassword" placeholder="密码" allow-clear>
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>

        <div class="form-extra">
          <a-link @click="showContactAdmin">忘记密码？</a-link>
        </div>

        <a-button type="primary" html-type="submit" long :loading="loading"> 登录 </a-button>
      </a-form>

      <div class="divider">
        <span>或者</span>
      </div>

      <!-- <div class="other-login">
        <a-button long @click="handleGiteeLogin">
          <template #icon>
            <svg viewBox="0 0 1024 1024" width="16" height="16" class="gitee-icon">
              <path
                d="M512 1024C229.222 1024 0 794.778 0 512S229.222 0 512 0s512 229.222 512 512-229.222 512-512 512z m259.149-568.883h-290.74a25.293 25.293 0 0 0-25.292 25.293l-0.026 63.206c0 13.952 11.315 25.293 25.267 25.293h177.024c13.978 0 25.293 11.315 25.293 25.267v12.646a75.853 75.853 0 0 1-75.853 75.853h-240.23a25.293 25.293 0 0 1-25.267-25.293V417.203a75.853 75.853 0 0 1 75.827-75.853h353.946a25.293 25.293 0 0 0 25.267-25.292l0.077-63.207a25.293 25.293 0 0 0-25.268-25.293H417.152a189.62 189.62 0 0 0-189.62 189.645V771.15c0 13.977 11.316 25.293 25.294 25.293h372.94a170.65 170.65 0 0 0 170.65-170.65V480.384a25.293 25.293 0 0 0-25.293-25.267z"
                fill="currentColor"
              />
            </svg>
          </template>
          使用 Gitee 账号登录
        </a-button>
      </div> -->

      <div class="footer-links">
        <a-link @click="goToHelp">帮助文档</a-link>
        <a-link @click="goToRegister">注册账号</a-link>
        <a-link @click="showContactAdmin">联系管理员</a-link>
      </div>
    </div>
  </div>

  <a-modal v-model:visible="contactVisible" title="联系管理员" @ok="handleContactSubmit">
    <a-form :model="contactForm" layout="vertical">
      <a-form-item label="您的邮箱" field="email">
        <a-input v-model="contactForm.email" placeholder="请输入您的邮箱" />
      </a-form-item>
      <a-form-item label="申请原因" field="reason">
        <a-textarea
          v-model="contactForm.reason"
          placeholder="请简要说明关于账号的需求（忘记密码、需要账号）"
          :auto-size="{ minRows: 3, maxRows: 5 }"
        />
      </a-form-item>
      <div class="contact-tips">
        <p>您也可以通过以下方式联系管理员：</p>
        <ul>
          <li>邮箱：admin@example.com</li>
          <li>微信：exampleWx</li>
          <li>工作时间：周一至周五 9:00-18:00</li>
        </ul>
      </div>
    </a-form>
  </a-modal>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  background: #f6f8fa;
}

.header {
  margin-bottom: 40px;
}

.logo {
  font-size: 32px;
  font-weight: bold;
  color: #1a1a1a;
}

.login-box {
  width: 340px;
  padding: 16px;
}

.title {
  font-size: 24px;
  font-weight: 300;
  letter-spacing: -0.5px;
  text-align: center;
  margin-bottom: 20px;
}

.login-form {
  background: #fff;
  border: 1px solid #d0d7de;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 16px;
}

.form-header {
  margin-bottom: 16px;
  text-align: center;
}

.form-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.form-extra {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 16px;
}

.divider {
  position: relative;
  text-align: center;
  margin: 16px 0;
}

.divider::before,
.divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: calc(50% - 24px);
  height: 1px;
  background: #d0d7de;
}

.divider::before {
  left: 0;
}

.divider::after {
  right: 0;
}

.divider span {
  background: #f6f8fa;
  padding: 0 8px;
  color: #57606a;
  font-size: 12px;
}

.other-login {
  margin-bottom: 16px;
}

.footer-links {
  display: flex;
  justify-content: center;
  gap: 16px;
  font-size: 12px;
}

.contact-tips {
  margin-top: 16px;
  padding: 12px;
  background: #f6f8fa;
  border-radius: 4px;
  font-size: 13px;
}

.contact-tips p {
  margin: 0 0 8px 0;
  color: #666;
}

.contact-tips ul {
  margin: 0;
  padding-left: 20px;
  color: #666;
}

.contact-tips li {
  line-height: 1.8;
}

.gitee-icon {
  margin-right: 8px;
  vertical-align: -0.125em;
}

.other-login .arco-btn:hover .gitee-icon {
  color: var(--color-primary-light-4);
}
</style>
